﻿using jbt.CodeCandy.AsTrEAM.Contracts;
using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace jbt.CodeCandy.AsTrEAM.WCF
{
    /// <summary>
    /// Implements <see cref="IStreamManagerService"/> by using an <see cref="IStreamManager"/> object.
    /// </summary>
    public class StreamManagerService : IStreamManagerService
    {
        private static readonly IStreamManager _streamManager = StreamManagerFactory.Create();

        #region IStreamManagerService Members

        async Task<StreamData> IStreamManagerService.Download(StreamDownloadRequest streamRequest)
        {
            if (streamRequest == null)
            {
                throw new ArgumentNullException("steamRequest");
            }

            var streamData = await _streamManager.Get(streamRequest.Id);

            return streamData;
        }

        async Task<NewStreamResult> IStreamManagerService.Upload(StreamData streamData)
        {
            if (streamData == null)
            {
                throw new ArgumentNullException("streamData");
            }

            try
            {
                var newStreamTask = await _streamManager.Create(streamData);

                return newStreamTask;
            }
            catch (Exception exception)
            {
                var streamFault = new StreamFault();
                streamFault.Message = exception.Message;
                var reason = exception.Message;

                throw new FaultException<StreamFault>(streamFault, reason);
            }
        }

        #endregion
    }
}